﻿using AutoMapper;
using B.S.Base.Write.API.Application.Command;
using MediatR;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture.Infasetures;

namespace B.S.Base.Write.API.Application.CommandHandLer
{
    public class AddRoleaccountCommandHandLer : IRequestHandler<AddRoleaccountCommand, APIResult<object>>
    {

        IBaseRepostiy<UserRoleModel> _userRoleModel;
        IMapper mapper;
        public AddRoleaccountCommandHandLer(IBaseRepostiy<UserRoleModel> userRoleModel, IMapper mapper)
        {
            _userRoleModel = userRoleModel;
            this.mapper = mapper;
        }

        public async  Task<APIResult<object>> Handle(AddRoleaccountCommand request, CancellationToken cancellationToken)
        {
            // 先去重
            var distinctAccountIds = request.AccountId.Distinct().ToList();

            // 查询已存在的账号-角色关系
            var existingUserRoles = _userRoleModel.GetAll().Where(x => x.RoleId == request.RoleId).Select(x => x.AccountId).ToHashSet();

            // 只添加未分配该角色的账号
            foreach (var accountId in distinctAccountIds)
            {
                if (!existingUserRoles.Contains(accountId))
                {
                    var newUserRole = new UserRoleModel()
                    {
                        AccountId = accountId,
                        RoleId = request.RoleId,
                    };
                    await _userRoleModel.AddAsync(newUserRole);
                }
            }
            return new APIResult<object>()
            {
                Code=ResultCode.Ok,
                Data=1,
                Message="分配成功"
            };
        }
    }
}
